package com.demo.project_template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.demo.project_template.entity.Post;
import com.demo.project_template.entity.PostComment;
import com.demo.project_template.entity.PostNotice;
import com.demo.project_template.mapper.PostCommentMapper;
import com.demo.project_template.mapper.PostMapper;
import com.demo.project_template.mapper.PostNoticeMapper;
import com.demo.project_template.service.PostCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javafx.geometry.Pos;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 帖子评论 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:57
 */
@Service
public class PostCommentServiceImpl extends ServiceImpl<PostCommentMapper, PostComment> implements PostCommentService {
    @Resource
    private PostMapper postMapper;
    @Resource
    private PostNoticeMapper postNoticeMapper;

    @Override
    public void add(PostComment postComment) {
        //保存评论
        save(postComment);
        //动态评论量+1
        postMapper.addCommentCount(postComment.getPostId());
        //添加动态通知
        PostNotice postNotice = new PostNotice();
        postNotice.setPostId(postComment.getPostId());
        postNotice.setUserId(postComment.getUserId());
        postNotice.setUserAvater(postComment.getUserAvater());
        postNotice.setUserNickName(postComment.getUserNickName());
        postNotice.setType("2");
        postNotice.setCommentId(postComment.getId());
        postNotice.setState("0");
        postNoticeMapper.insert(postNotice);
    }

    @Override
    public List<PostComment> listChildComments(Long commentPid) {
        List<PostComment> postComments = list(new LambdaQueryWrapper<PostComment>().eq(PostComment::getPid, commentPid));
        if (!postComments.isEmpty()){
            postComments.forEach(this::pathChild);
        }
        return postComments;
    }

    private void pathChild(PostComment parent){
        List<PostComment> child = list(new LambdaQueryWrapper<PostComment>().eq(PostComment::getPid, parent.getId()));
        if (child.isEmpty()){
            return;
        }
        child.forEach(this::pathChild);
        parent.setChildComment(child);
    }
}
